<template>
  <div class="user">
    <el-form :rules="rules" :model="rule" ref="rule">
      <el-form-item label="账号:" prop="username">
        <el-input type="text" v-model="rule.username" clearable autocomplete="off"></el-input>
      </el-form-item>
      <el-form-item label="密码:" prop="password">
        <el-input type="password" v-model="rule.password" show-password autocomplete="off"></el-input>
      </el-form-item>
    </el-form>
    <div class="regi">
      <p>忘记密码？</p>
      <p @click="$router.push(register.path)">没有账号？注册新账号</p>
    </div>
    <btn :name="register.name" @click.native="login" />
  </div>
</template>

<script>
import btn from "../components/btn";

export default {
  name: "email",
  components: {
    btn
  },
  data() {
    function username(rule, value, callback) {
      if (/^[A-z][A-z0-9]{4,14}$/.test(value)) callback();
      else callback("账号输入错误");
    }
    function password(rule, value, callback) {
      if (/^[A-z0-9]{4,14}$/.test(value)) callback();
      else callback("密码输入错误");
    }
    return {
      rule: {
        username: "",
        password: ""
      },
      rules: {
        username: [{ validator: username, trigger: "blur" }],
        password: [{ validator: password, trigger: "blur" }]
      },
      register: {
        path: "/login/register",
        name: "登录"
      }
    };
  },
  methods: {
    login() {
      this.$refs["rule"].validate(state => {
        if (state) {
          this.$http.post("/login_pc/", this.rule).then(res => {
            if (res.data.code === 0) {
              this.$message({
                type: "success",
                message: res.data.msg
              });
              console.log(res.data)
              let token = res.data.token;
              this.$cookie.set("login_tk", token);
              this.$store.commit("addcookie", token);
              // this.$store.dispatch("promission/generatorRoutes")
              this.$router.push("/")
              this.rule.username = "";
              this.rule.password = "";
            } else {
              this.$message.error(res.data.msg);
            }
          });
        } else {
          this.$message.error("你还没输入");
        }
      });
    }
  }
};
</script>

